//
//  TQQTouchLabel.swift
//  SwiftLearning
//
//  Created by 黄龙 on 2024/1/26.
//

import UIKit

protocol TQQTouchLabelDelegate: AnyObject {
    func touchDown(_ sender:TQQTouchLabel)
    func touchOut(_ sender:TQQTouchLabel)
    func touchUpInside(_ sender:TQQTouchLabel)
}


class TQQTouchLabel: UILabel {
    weak var delegate: TQQTouchLabelDelegate?
    @objc var timeoffset:CFTimeInterval = 0
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        delegate?.touchDown(self)
        print("TQQTouchLabel.touchDown")
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {return}
        let locationInView = touch.location(in: self.superview) //取触摸点相对于当前视图的位置,Y是负的
        if frame.contains(locationInView){
            delegate?.touchUpInside(self)
            print("TQQTouchLabel[end].touchUpInside.1")
        }
        else if let rect = self.layer.presentation()?.frame{
            if CGRectContainsPoint(rect, locationInView){
                delegate?.touchUpInside(self)
                print("TQQTouchLabel[end].touchUpInside.2")
            }else{
                delegate?.touchOut(self)
                print("TQQTouchLabel[end].touchOut")
            }
        }
        else{
            delegate?.touchOut(self)
            print("TQQTouchLabel[end].touchOut")
        }
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else {return}
        let locationInView = touch.location(in: self.superview) //取触摸点相对于当前视图的位置
        if frame.contains(locationInView){
            delegate?.touchUpInside(self)
            print("TQQTouchLabel[cancel].touchUpInside.1")
        }
        else if let rect = self.layer.presentation()?.frame{
            if CGRectContainsPoint(rect, locationInView){
                delegate?.touchUpInside(self)
                print("TQQTouchLabel[cancel].touchUpInside.2")
            }else{
                delegate?.touchOut(self)
                print("TQQTouchLabel[cancel].touchOut")
            }
        }
        else{
            delegate?.touchOut(self)
            print("TQQTouchLabel[cancel].touchOut")
        }
    }

}
